// 监听安装事件
chrome.runtime.onInstalled.addListener(() => {
    // 初始化存储
    chrome.storage.local.set({
        isLocked: true,
        passwords: [],
        settings: {
            autoLockTime: 5, // 分钟
            passwordLength: 16
        }
    });
});

// 自动锁定计时器
let lockTimer;

// 监听来自content script的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    switch (request.action) {
        case 'checkCredentials':
            checkExistingCredentials(request.data, sendResponse);
            return true;

        case 'getCredentials':
            getCredentialsForSite(request.url, sendResponse);
            return true;

        case 'saveCredentials':
            saveCredentials(request.data, sendResponse);
            return true;

        case 'resetLockTimer':
            resetLockTimer();
            return true;
    }
});

// 检查凭据是否已存在
function checkExistingCredentials(credentials, callback) {
    chrome.storage.local.get(['passwords'], result => {
        const passwords = result.passwords || [];
        const exists = passwords.some(p => 
            p.website === credentials.website && 
            p.username === credentials.username
        );
        callback({ exists });
    });
}

// 获取网站的已保存凭据
function getCredentialsForSite(url, callback) {
    chrome.storage.local.get(['passwords', 'isLocked'], result => {
        if (result.isLocked) {
            callback({ error: 'Password manager is locked' });
            return;
        }

        const passwords = result.passwords || [];
        const siteCredentials = passwords.filter(p => p.website === url);
        
        callback({ 
            credentials: siteCredentials.length === 1 ? siteCredentials[0] : siteCredentials
        });
    });
}

// 保存新凭据
function saveCredentials(credentials, callback) {
    chrome.storage.local.get(['passwords', 'isLocked'], result => {
        if (result.isLocked) {
            callback({ error: 'Password manager is locked' });
            return;
        }

        const passwords = result.passwords || [];
        const existingIndex = passwords.findIndex(p => 
            p.website === credentials.website && 
            p.username === credentials.username
        );

        if (existingIndex >= 0) {
            passwords[existingIndex] = {
                ...passwords[existingIndex],
                ...credentials,
                lastModified: new Date().toISOString()
            };
        } else {
            passwords.push({
                ...credentials,
                id: Date.now().toString(),
                createdAt: new Date().toISOString(),
                lastModified: new Date().toISOString()
            });
        }

        chrome.storage.local.set({ passwords }, () => {
            callback({ success: true });
        });
    });
}

// 重置自动锁定计时器
function resetLockTimer() {
    clearTimeout(lockTimer);
    chrome.storage.local.get(['settings'], result => {
        const autoLockTime = (result.settings?.autoLockTime || 5) * 60 * 1000; // 转换为毫秒
        lockTimer = setTimeout(() => {
            chrome.storage.local.set({ isLocked: true });
        }, autoLockTime);
    });
}

// 监听标签页更新，用于处理页面刷新和导航
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
    if (changeInfo.status === 'complete' && tab.url) {
        chrome.scripting.executeScript({
            target: { tabId },
            function: () => {
                // 触发重新检测表单
                document.dispatchEvent(new Event('DOMContentLoaded'));
            }
        }).catch(() => {
            // 忽略无法注入脚本的错误（比如在chrome://页面）
        });
    }
});
